package com.test.config;

import com.test.filter.JwtFilter;
import com.test.realms.MyRealm;
import com.test.redis.RedisCacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ssang
 * @date 2021-12-09 10:50
 */
@Configuration
public class ShiroConfig {
    //创建过滤器，拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //向shiro中添加自定义的过滤器
        Map filterMap = new HashMap();
//        filterMap.put("jwtFilter",new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        //设置角色和资源等权限
        Map map = new HashMap<>();
//        map.put("/**","jwtFilter");//设置所有请求通过jwtFilter
        map.put("/index.jsp","authc");
        map.put("/login/getImage","anon");//验证码
        shiroFilterFactoryBean.setLoginUrl("login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    //创建安全管理器
    @Bean
    public DefaultWebSecurityManager getSecurityManager(Realm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    //创建自定义的Realm
    @Bean("myRealm")
    public Realm getRealm(){
        MyRealm myRealm = new MyRealm();

        //设置hashed凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");//加密方式md5
        credentialsMatcher.setHashIterations(1024);//散列次数，1024

        myRealm.setCredentialsMatcher(credentialsMatcher);

        //开启缓存，设置缓存管理器
        myRealm.setCachingEnabled(true);
        myRealm.setAuthenticationCachingEnabled(true);
        myRealm.setAuthorizationCachingEnabled(true);
//        myRealm.setCacheManager(new EhCacheManager());
        myRealm.setCacheManager(new RedisCacheManager());

        return myRealm;
    }
}
